<template>
  <view class="mail-list" :class="{selected: selected.length > 0}">
    <u-index-list :scrollTop="scrollTop" active-color="#FBB000" :index-list="indexList">
      <view v-for="(item, index) in contacts" :key="index">
        <u-index-anchor :index="item.letter" />
        <block v-for="(i, k) in item.contacts" :key="k">
          <view class="list-cell" @click="onChangeItem(index, k)">
            <view class="radio" :class="{active: i.selected}">
              <u-icon name="checkmark" color="#fff" size="24"></u-icon>
            </view>
            <text>{{i.name}}</text>
          </view>
        </block>
      </view>
    </u-index-list>
    
    <!-- 确定 -->
    <view class="footer" v-if="selected.length > 0">
      <view class="btn-box">
        <view class="btn flex flex-ai-c flex-jc-c" @click="onClickSendSms">
          <text class="text">确定</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import pinyin from '@/utils/pinyin/pinyin3.js'
let platform = uni.getSystemInfoSync().platform
export default {
  data() {
    return {
      scrollTop: 0,
      /* 联系人 */
      contacts: [],
      contactItems: [],
      indexList: [],
      selected: [] ,// 已选联系人
      inviteLink: 'https://files.yzsheng.com/shareH5/Qmc_Client_H5_member/membersPage.html' // 邀请链接
    }
  },
  onLoad(option) {
    if(option.inviteCode && option.name) {
      this.inviteLink += '?code=' + option.inviteCode + '&name=' + option.name
    } else {
      this.$api.user.GetUserInfomation().then(data => {
        this.inviteLink = '?code=' + data.data.invitecode + '&name=' + data.data.nickname
      }).catch(err => {})
    }
    this.initContacts()
  },
  methods: {
    /* 
     * 初始化通讯录
     */
    initContacts() {
      //获取手机通讯录
      plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, (addressbook) => {
        // 可通过addressbook进行通讯录操作
        addressbook.find(["displayName", "phoneNumbers"], (contacts) => {
          let items = [];
          for (let i = 0; i < contacts.length; i++) {
            if (contacts[i].phoneNumbers.length > 0) {
              let contact = {
                'name': contacts[i].displayName,
                'phone': contacts[i].phoneNumbers[0].value,
                'selected': false
              };
              items.push(contact);
            }
          }
          this.contacts = pinyin.paixu(items)
          this.contacts.sort(function(o1, o2) {
            return o1.letter.charCodeAt(0) - o2.letter.charCodeAt(0)
          })
          this.contactItems = JSON.parse(JSON.stringify(this.contacts))
          this.indexList = this.contactItems.map(item => {
            return item.letter
          })
        }, (e) => {
          this.onAddressBookSetting()
        });
      }, (e) => {
        this.onAddressBookSetting()
      });
    },
    /*
     * 权限设置
     */
    onAddressBookSetting() {
      if (this.isShow) {
        return
      }
      this.isShow = true
      uni.showModal({
        title: '提示',
        content: 'APP通讯录权限没有开启，是否开启？',
        success(res) {
          if (res.confirm) {
            if (platform == 'ios') {
              var UIApplication = plus.ios.import("UIApplication");
              var NSURL2 = plus.ios.import("NSURL");
              var setting2 = NSURL2.URLWithString("app-settings:");
              var application2 = UIApplication.sharedApplication();
              application2.openURL(setting2);
              plus.ios.deleteObject(setting2);
              plus.ios.deleteObject(NSURL2);
              plus.ios.deleteObject(application2);
            } else {
              var main = plus.android.runtimeMainActivity();
              var bulid = plus.android.importClass("android.os.Build");
              var Intent = plus.android.importClass('android.content.Intent');
              if (bulid.VERSION.SDK_INT >= 9) {
                var intent = new Intent('android.settings.APPLICATION_DETAILS_SETTINGS');
                var Uri = plus.android.importClass('android.net.Uri');
                var uri = Uri.fromParts("package", main.getPackageName(), null)
                intent.setData(uri);
                intent.putExtra('android.content.Intent.setFlags', Intent.FLAG_ACTIVITY_NEW_TASK);
              } else if (bulid.VERSION.SDK_INT <= 8) {
                var intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                intent.putExtra("com.android.settings.ApplicationPkgName", main.getPackageName());
                intent.putExtra('android.content.Intent.setFlags', Intent.FLAG_ACTIVITY_NEW_TASK);
              }
              main.startActivity(intent);
              this.isShow = false
            }
          } else {
            uni.navigateBack({
              delta: 1
            })
          }
        }
      })
    },
    // 点击联系人
    onChangeItem(parent, current) {
      let list = this.contacts
      let select = []
      list[parent].contacts[current].selected = !list[parent].contacts[current].selected
      this.contacts = list
      list.map(item => {
        item.contacts.map(i => {
          if(i.selected) {
            select.push(i.phone)
          }
        })
      })
      this.selected = select
    },
    // 发送短信
    async onClickSendSms() {
      uni.showLoading({
        title: '发送中'
      })
      // let msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);
      // msg.to = this.selected
      // msg.body = 'This is HTML5 Plus example test message'
      // plus.messaging.sendMessage(msg, () => {
      //   uni.hideLoading()
      //   uni.showToast({
      //     icon: 'none',
      //     title: '短信发送成功'
      //   })
      //   setTimeout(() => {
      //     uni.navigateBack({
      //       delta: 2
      //     })
      //   }, 1500)
      // }, () => {
      //   uni.hideLoading()
      //   uni.showToast({
      //     icon: 'none',
      //     title: '短信发送失败'
      //   })
      // })
      try{
        let res = await this.$api.user.SendInviteMember({
          mobile: this.selected,
          originURL: this.inviteLink
        })
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: res.data
        })
      }catch(e){
        uni.hideLoading()
      }
    }
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  }
}
</script>

<style lang="scss" scoped>
.mail-list{
  overflow: hidden;
  .list-cell {
    display: flex;
    box-sizing: border-box;
    width: 100%;
    padding: 10px 24rpx;
    overflow: hidden;
    color: #333;
    font-size: 14px;
    line-height: 24px;
    background-color: #fff;
    align-items: center;
    border-top: 1px solid whitesmoke;
    .radio{
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      width: 36rpx;
      height: 36rpx;
      border-radius: 36rpx;
      border: 2rpx solid #d0d0d0;
      margin-right: 20rpx;
      &.active{
        background: linear-gradient(0deg, #FBD220, #FFE23E);
        border: none;
      }
    }
  }
  &.selected {
    padding-bottom: 120rpx;  
    padding-bottom: calc(constant(safe-area-inset-bottom) + 120rpx);  
    padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);
  }
  .footer{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding-bottom: 0;  
    padding-bottom: constant(safe-area-inset-bottom);  
    padding-bottom: env(safe-area-inset-bottom);
    background-color: #fff;
    .btn-box{
      padding: 16rpx 24rpx;
      .btn{
        height: 88rpx;
        background: linear-gradient(0deg, #FBD220, #FFE23E);
        border-radius: 44rpx;
        .text{
          font-size: 32rpx;
          color: #333;
          margin-left: 16rpx;
        }
      }
    }
  }
}
</style>
